package net.zjitc.list;

public class MyArrayList<T> implements MyList<T> {
    private Object[] arr = new Object[2];
    private int size = 0;


    @Override
    public boolean add(T data) {
        //如果数组空间不够怎么办？扩容
        capacity();

        arr[size++] = data;
        return true;
    }

    private void capacity() {
        if (size >= arr.length) {
            Object[] temp = new Object[size * 2];
            for (int i = 0; i < size; i++) {
                temp[i] = arr[i];
            }
            arr = temp;
        }
    }


    @Override
    public boolean add(int index, T data) {
        //索引不在范围怎么办？比如为-1？
        checkPositionIndex(index);
        //空间不够怎么办？
        capacity();
        //如何插入一个元素？？
        for (int i = size; i >index ; i--) {
            arr[i] = arr[i-1];
        }
        arr[index] = data;
        size++;

        return true;
    }



    @Override
    public T remove(T data) {
        T oldData = null ;
       // data.equals();
        for (int i = 0; i < size; i++) {
            if (data==arr[i] || data.equals(arr[i])){
                oldData = (T) arr[i];
                for (int j = i; j < size-1; j++) {
                     arr[j] = arr[j+1];
                }
                break;
            }
        }
        size--;
        return oldData;
    }

    /**
     * 删除指定位置的元素
     * @param index
     * @return
     */
    @Override
    public T remome(int index) {
        checkElementIndex(index);
        //删除
        //。。。。。
        T oldData = (T) arr[index] ;
        for (int j = index; j < size-1; j++) {
            arr[j] = arr[j+1];
        }
        size--;
        return oldData;
    }

    @Override
    public boolean set(int index, T data) {
        checkElementIndex(index);

        arr[index] = data;
        return true;
    }


    @Override
    public T getValue(int index) {
        checkElementIndex(index);

        return (T) arr[index];
    }

    @Override
    public int size() {
        return size;
    }


    /**
     * 检测元素位置是否越界
     * @param index
     */
    private void checkElementIndex(int index) {
        if (index<0 || index>=size){
            throw new RuntimeException("取元素的位置越界");
        }
    }

    /**
     * 检测插入点是否越界
     * @param index
     */
    private void checkPositionIndex(int index) {
        if (index<0 || index>size){
            throw new RuntimeException("索引越界");
        }
    }
}
